<?php


namespace app\crm\model;

use app\mini\model\CustomerPointModel;
use think\facade\Db;
use app\admin\model\Common;

class Service extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'service';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataList(array $request): array
    {


        // echo "<pre>";
        //   print_r($request);exit;
        //echo  '当前时间000--'.time();//exit;
        // try {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        $customerId       = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : '';

        $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;
        // echo "是否导出：".$is_export;
        // exit;

        // print_r($request);exit;
        $shopId = isset($request['shop_id']) && intval($request['shop_id']) ? intval($request['shop_id']) : 0;
        $shopIds = $request['shopIds'] ?? [];
        $where      = [];
        $mini = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

        if($mini == 0){
            $customerId && array_push($where, ['customer_id', '=', $customerId]);
        }else{
            $telephone222 = Db::name('customer')->where('id', '=', $customerId)->value('telephone');
            $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');
            array_push($where, ['customer_id', 'in', $customerIds222]);
        }
        $shopId && array_push($where, ['shop_id', '=', $shopId]);

        array_push($where, ['status', '=', 1]);

        if($shopIds){
            array_push($where, ['shop_id', 'in', $shopIds]);
        }
        $start_time = $request['start_time'] ?? '';
        if($start_time){
            array_push($where, ['create_time', '>=', strtotime($start_time)]);
        }
        $end_time = $request['endTime'] ?? '';
        if($end_time){
            array_push($where, ['create_time', '<=', strtotime($end_time)]);
        }
        $customer_name = $request['customer_name'] ?? '';
        if($customer_name){
            $customerIds = Db::name('customer')->where('customer_name','like','%'.$customer_name.'%')->column('id');
            array_push($where, ['customer_id', 'in', $customerIds]);
        }
        $telephone = $request['telephone'] ?? '';
        if($telephone){
            $customerIds = Db::name('customer')->where('telephone','=',$telephone)->column('id');
            array_push($where, ['customer_id', 'in', $customerIds]);
        }
        $effective = $request['effective'] ?? 0;
        if($effective){
            $end_time = 24*60*60*$effective+time();
            array_push($where, ['end_time', '<=', $end_time]);
        }
        $shopIds = $request['shopIds'] ?? [];
        if($shopIds){
            array_push($where,['shop_id','in',$shopIds]);
        }

        $card_name = isset($request['name']) ? $request['name'] : ''; //开卡名称
        if($card_name){
            array_push($where,['name','like',$card_name.'%']);
        }

        $dataCount = $this->where($where)->count();

        if ($dataCount) {
            $field = [];

            if($is_export == '1'){

                if($shopId == '0'){

                    if($shopIds){
                        $list  = $this->where($where)->select()->toArray();
                    }else{
                        $list = [];
                    }

                    // $this->error = '请选择门店！！！';
                }else{

                    $list  = $this->where($where)->select()->toArray();
                }
                // $list  = $this->where($where)->select()->toArray();
                // ->field($field)->order('id DESC')
                // ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

            }else{
                $list  = $this->where($where)->field($field)->order('id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
            }

            $customerIdArr = array_values(array_unique(array_column($list, 'customer_id')));
            $customerWhere = [
                ['id', 'in', $customerIdArr]
            ];
            $customerList = Db::name('customer')->where($customerWhere)->column('customer_name', 'id');
            $kk_user_idArr = array_values(array_unique(array_column($list, 'kk_user_id')));
            $personList = Db::name('shop_person')->where('id','in',$kk_user_idArr)->column('name', 'id');

            $shop_idArr = array_values(array_unique(array_column($list, 'shop_id')));
            $shopList = Db::name('shop')->where('shop_id','in',$shop_idArr)->column('shop_name', 'shop_id');
            //查询登录员工是否是 门诊

            $loginstaffList = Db::name('admin_user')->where('id','=',$request['user_id'])->column('shop_id,id,realname');


            //获取登录员工的 部门归属
            $shopTypeList = Db::name('shop')->where('shop_id','=',$loginstaffList[0]['shop_id'])->column('shop_type,shop_id');


            $serviceIdArr = array_values(array_unique(array_column($list, 'id')));
            $map =[];
            if(!empty($request['user_shop_id'])){
                $map['is_cancel'] = 0;
            }
            $service_logList = Db::name('service_log')->where($map)->group('service_id')->column(['count(id)'], 'service_id');

            $serviceTypeArr = ['1' => '按期', '2' => '按次'];
            foreach ($list as $key => $val) {
                $list[$key]['customer_name']     = $customerList[$val['customer_id']] ?? '';
                $list[$key]['service_type_name'] = $serviceTypeArr[$val['service_type']] ?? '';
                $list[$key]['last_service_time'] = $val['last_service_time'] ? date('Y-m-d H:i:s', $val['last_service_time']) : '';
                $list[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                $list[$key]['end_time']     = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                // $list[$key]['comment_time']     = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                $list[$key]['sy_num']       = $service_logList[$val['id']] ?? 0;
                $list[$key]['yy_num']       = bcsub($val['num'],$list[$key]['sy_num']);
                $list[$key]['kk_user_name'] = $personList[$val['kk_user_id']] ?? '';
                $list[$key]['shop_name'] = $shopList[$val['shop_id']] ?? '';

                $list[$key]['shop_type'] = $shopTypeList[0]['shop_type'] ?? '';

                //查询登录员工的归属信息
                if($mini == 0){
                    $logusershop = Db::name('admin_user')->alias('au')
                        ->join('shop_person sp', 'au.shop_person_id=sp.id', 'LEFT')
                        ->where('au.id','=',$request['user_id'])
                        ->where('au.is_status','=',0)
                        ->column('sp.shop_id as shopID,sp.id');

                    $list[$key]['shopid_U'] = $logusershop[0]['shopID'];
                }else{
                    $list[$key]['shopid_U'] = $val['shop_id'];
                }

            }
        }

        //die;
        /* echo "<pre>";
          print_r($list);
          exit; */
        //var_dump($list);
        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
        // } catch (\Exception $e) {
        // }

        $this->error = '暂无此数据';
        return [];
    }


    /**
     * 添加
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataInfo(array $request): array
    {
        // try {
            $serviceId = $request['id'] ?? 0;
            if (!$serviceId) {
                $this->error = '参数错误';
                return [];
            }

            $info = $this->where('id', '=', $serviceId)->find();
            if (!$info) {
                $this->error = '暂无数据';
                return [];
            }
            $info = $info->toArray();
            $serviceTypeArr = ['1' => '按期', '2' => '按次'];
            $customerInfo   = Db::name('customer')->where('id', '=', $info['customer_id'])->find();
            $info['customer_name']     = $customerInfo['customer_name'] ?: '';
            $info['service_type_name'] = $serviceTypeArr[$info['service_type']] ?? '';
            $info['last_service_time'] = $info['last_service_time'] ? date('Y-m-d H:i:s', $info['last_service_time']) : '';
            $info['start_time']        = $info['start_time'] ? date('Y-m-d H:i:s', $info['start_time']) : '';
            $info['end_time']          = $info['end_time'] ? date('Y-m-d H:i:s', $info['end_time']) : '';

            $logWhere = [
                ['service_id', '=', $serviceId]
            ];
            $shopInfo   = Db::name('shop')->where('shop_id', '=', $info['shop_id'])->find();
            $logList = Db::name('service_log')->where($logWhere)->select()->toArray();
            if ($logList) {
                $oneId     = array_column($logList, 'nurse_id_one');
                $twoId     = array_column($logList, 'nurse_id_two');
                $userIdArr = array_unique(array_merge($oneId, $twoId));
                $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
                $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
                foreach ($logList as $key => $val) {
                    $logList[$key]['nurse_id_one_name'] = $userList[$val['nurse_id_one']] ?? '';
                    $logList[$key]['nurse_id_two_name'] = $userList[$val['nurse_id_two']] ?? '';
                    $logList[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $logList[$key]['end_time']          = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $logList[$key]['create_time']       = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '';
                    $logList[$key]['comment_time']      = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                    $logList[$key]['customer_name']     = $customerInfo['customer_name'];
                    $logList[$key]['sex']               = $customerInfo['sex'] == 1? '男':'女';
                    $logList[$key]['age']               = $customerInfo['age'];
                    $logList[$key]['shop_name']         = $shopInfo['shop_name'];
                    $logList[$key]['market_name']       = $shopInfo['market_name'];
                    $logList[$key]['nurse_name']        = $userList[$customerInfo['nurse_id']] ?? '';
                    $logList[$key]['name']        = $info['name'];
                    $logList[$key]['experience']  = $info['experience']==1?'体验':'服务';
                    $logList[$key]['pt']  = $val['pt']==1?'手机':'PC电脑';
                    $createName = Db::name('admin_user')->where('id','=',$val['create_id'])->value('realname');
                    $logList[$key]['createName']  = $createName ?? '';
                    $logList[$key]['fw_num']  = 1;
                }
            }
            $info['service_log'] = $logList;

            return $info;
        // } catch (\Exception $e) {
        // }

        return [];
    }
	/**

	 * 获取服务记录

	 * @param  array $request 请求参数

	 * @return array

	 */
	public function getDataLog(array $request): array
	{

		$request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

		$request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

		$customerId       = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : '';


		$shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

        $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;

        $is_delete = isset($request['is_delete']) && intval($request['is_delete']) ? intval($request['is_delete']) : 0;

        $hexiaotype = isset($request['hexiaotype']) && intval($request['hexiaotype']) ? intval($request['hexiaotype']) : '';

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // echo "搜索门店id为：".$shopId;
        // exit;

		$shopIds = $request['shopIds'] ?? [];

		$where      = [];
		$whereOr    = [];


		$customerId && array_push($where, ['customer_id', '=', $customerId]);

		$shopId && array_push($where, ['shop_id', '=', $shopId]);

        // $shopId && array_push($where, ['shop_id', '=', $shopId]);

		if($shopIds){

			array_push($where, ['shop_id', 'in', $shopIds]);

		}

		$start_time = $request['start_time'] ?? '';

		if($start_time){

			$startTime =strtotime($request['start_time']);
			array_push($where, ['create_time', '>=', $startTime]); //
            array_push($where, ['create_time', '>=', '1654012800']);

		}

		$endTime = $request['endTime'] ?? '';

		if($endTime){

			$endTime =strtotime($request['endTime'])+83699;

			array_push($where, ['create_time', '<=', $endTime]);

		}

		//var_dump($where);

		$customer_name = $request['customer_name'] ?? '';

		if($customer_name){

			$customerIds = Db::name('customer')->where('customer_name','like','%'.$customer_name.'%')->column('id');

			array_push($where, ['customer_id', 'in', $customerIds]);

		}

		$telephone = $request['telephone'] ?? '';

		if($telephone){

			$customerIds = Db::name('customer')->where('telephone','=',$telephone)->column('id');

			array_push($where, ['customer_id', 'in', $customerIds]);

		}

		$nurse_name = $request['nurse_name'] ?? '';

		if($nurse_name){

			$shop_personT = Db::name('shop_person')->where('name','=',$nurse_name)->column('id');

			array_push($where, ['nurse_id_one', 'in', $shop_personT]);
			array_push($whereOr, ['nurse_id_two', 'in', $shop_personT]);
		}



		// $shopIds = $request['shopIds'] ?? [];

		// if($shopIds){

		// 	array_push($where,['shop_id','in',$shopIds]);

		// }
        if(!$is_delete)
        {
            array_push($where,['deleted_at','null','']);
        }

        if($hexiaotype){

            array_push($where,['service_type','=',$hexiaotype]);

        }

		// print_r($where);
		$dataCount = Db::name('service_log')->where($where)->whereOr($whereOr)->count();

		if ($dataCount) {

			$field = [];

            if($is_export == '1'){

                // if($shopId == '0'){

                //     $servicelog = [];

                // }else{



                // }

				//var_dump($start_time ,$endTime,$shopIds);

                if(!$start_time || !$endTime || !$shopId){

                    $this->error = '请选择导出时间和门店';
                    return [];

                }


                // array_push($where,['station_name','>','0']);

                $servicelog  = Db::name('service_log')->where($where)->whereOr($whereOr)->field($field)->order('id DESC')->select()->toArray();


            }else{
                $servicelog  = Db::name('service_log')->where($where)->whereOr($whereOr)->field($field)->order('id DESC')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->select()->toArray();
            }

			// echo "<pre>";
            // print_r($servicelog);
            // echo "</pre>";
            // exit;


		    $oneId     = array_column($servicelog, 'nurse_id_one');

		    $twoId     = array_column($servicelog, 'nurse_id_two');

		    $userIdArr = array_unique(array_merge($oneId, $twoId));

		    $userWhere = [

		        ['id', 'in', $userIdArr]

		    ];

		    $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');

			$goods_category= Db::name('shop_goods_category')->field('id,name')->select()->toArray();

			$goods_category=array_column($goods_category,null,'id');

			$sex = [
                '1' => '男',
                '2' => '女'
            ];

            $experience = [
                '1' => '体验',
                '2' => '服务'
            ];

		    foreach ($servicelog as $key => $val) {

				$customerInfo   = Db::name('customer')->where('id', '=', $val['customer_id'])->find();

				$shopInfo       = Db::name('shop')->where('shop_id', '=', $val['shop_id'])->find();

                $userInfo       = Db::name('admin_user')->where('id', '=', $val['cancel_staffId'])->find();

				$info = $this->where('id', '=', $val['service_id'])->find();

                $controlsInfo = Db::name('shop_person_controls')->column('name','id');

				$creatNM = Db::name('shop_person')->where('id','=',$val['create_id'])->value('name');

				$servicelog[$key]['create_time']       = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '';

				$servicelog[$key]['nurse_id_one_name'] = $userList[$val['nurse_id_one']] ?? '';

				$servicelog[$key]['nurse_id_two_name'] = $userList[$val['nurse_id_two']] ?? '';

				$servicelog[$key]['customer_name']     = $customerInfo['customer_name'] ?? '';

				$servicelog[$key]['sex']               = $sex[$customerInfo['sex']] ?? '';

				$servicelog[$key]['age']               = $customerInfo['age'] ?? '';

				$servicelog[$key]['shop_name']         = $shopInfo['shop_name'] ?? '';

				$servicelog[$key]['market_name']       = $shopInfo['market_name'] ?? '';

				$servicelog[$key]['nurse_name']        = $userList[$customerInfo['nurse_id']] ?? '';

				$servicelog[$key]['category_name']     = $goods_category[$val['category_id']]['name'];

				$servicelog[$key]['pt']                = $val['pt']==1?'小程序':'PC电脑';

                if($val['service_type'] == 2){

                    $servicelog[$key]['name']          = $controlsInfo[$val['service_id']] ?? '';

                    $servicelog[$key]['hexiaoType']    = '';

                }else{

                    $servicelog[$key]['name']          = $info['name'] ?? '';

                    $servicelog[$key]['hexiaoType']    = '';

                }

                $servicelog[$key]['mark']              = $val['mark'] ?? '';

				$servicelog[$key]['experience']        = $experience[$info['experience']] ?? '';

				$servicelog[$key]['createName']        = $createName ?? '';

				$servicelog[$key]['id']            =  $val['id'];
				$servicelog[$key]['fw_num']            = 1;
                $servicelog[$key]['cancel_realname'] = $userInfo['realname'] ?? '';
                if(empty($val['deleted_at']))
                {
                    $servicelog[$key]['status_msg'] = "正常";
                }else{
                    $servicelog[$key]['status_msg'] = "已作废";
                }

                $servicelog[$key]['mark'] = $val['mark'] != '0' ? $val['mark'] : "";
			}
		}


		$data              = [];

		$data['service_log']      = $servicelog ?? [];

		$data['dataCount']        = $dataCount ?? 0;

		return $data;

		/* $this->error = '暂无此数据';

		return []; */
	}


	/**

	 * 获取员工护理量统计

	 * @param  array $request 请求参数

	 * @return array

	 */
	public function getDataNursing(array $request): array
	{

		$request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

		$request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;


		$shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

        $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;

		$shopIds = $request['shopIds'] ?? [];

		$nowYear =  date('y'); //当前年
		$nowMonth =  date('m'); //当前月份
		$nowdata =  date('t'); //当前天数

		$startmonth = $nowYear.'-'.$nowMonth.'-'.'1';
		$endmonth = $nowYear.'-'.$nowMonth.'-'.$nowdata;

		$start_time = $request['start_time'] ?? '';
		if($start_time){

			$startTimeToday =strtotime($request['start_time']);
		}else{
			$startTimeToday =strtotime($startmonth);
		}

		$endTime = $request['endTime'] ?? '';

		if($endTime){

			$endTimeToday =strtotime($request['endTime'])+86399;
			$startDataTime = strtotime($request['endTime']);
			$endDataTime = strtotime($request['endTime'])+86399;

		}else{
			$endTimeToday =strtotime($endmonth)+86399;
			$startDataTime = strtotime(date('Y-m-d'));
			$endDataTime = strtotime(date('Y-m-d'))+86399;
		}

		$where      = [];

        $shopId && array_push($where, ['s.shop_id', '=', $shopId]);

		if($shopIds){

			array_push($where,['s.shop_id','in',$shopIds]);

		}

		$nurseName = $request['nurse_name'] ?? '';

		if($nurseName){

			array_push($where,['s.name','=',$nurseName]);

		}

		$category =$this->getPushCategoryArray();
		array_push($where, ['s.status', '=', 1]);
		//array_push($where, ['sp.type', '=', 1]);

		$dataCount = Db::name('shop_person')->alias('s')
			    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
			    ->where($where)->count();

		/*
			疤痘护理---- 1  | 面部护理---- 8 | 项目身体护理  ---10  | 生命之源/经络通/疏肝理气 --11 | 基础补水 --12
		*/

		if ($dataCount) {

			$field = ['s.id,s.shop_id,s.shop_name,s.name,s.market_name,s.station_name'];

            if($is_export == '1'){

                $list  = Db::name('shop_person')->alias('s')

                    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                    ->where($where)

                    ->field($field)->order('s.shop_id DESC')

                    ->select()->toArray();

            }else{

                $list  = Db::name('shop_person')->alias('s')

                    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                    ->where($where)

                    ->field($field)->order('s.shop_id DESC')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->select()->toArray();

            }

			// $list  = Db::name('shop_person')->alias('s')

			//     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

			//     ->where($where)

			// 	->field($field)->order('s.shop_id DESC')

			//     ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

			//     ->select()->toArray();

			$pids =array_column($list,'id');
			$category =$this->getPushCategoryArray();
			$ids =array_column($category,'id');

			// 获取当天服务量
			// 比例为1的
			$where = [];
			array_push($where,['category_id','in',$ids]);
			array_push($where,['nurse_id_one','in',$pids]);
			array_push($where,['nurse_id_two','=',0]);
			array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
			$arr1 =Db::name('service_log')
			    ->field('nurse_id_one as personId,category_id')
			    ->where($where)
			    ->select()->toArray();
			//print_r($arr1);
			// 比例为0.5的
			$where = [];
			array_push($where,['category_id','in',$ids]);
			array_push($where,['nurse_id_one','in',$pids]);
			array_push($where,['nurse_id_two','>',0]);
			array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
			$arr2 =Db::name('service_log')
			    ->field('nurse_id_one as personId,category_id')
			    ->where($where)
			    ->select()->toArray();
			$where = [];
			array_push($where,['category_id','in',$ids]);
			array_push($where,['nurse_id_two','in',$pids]);
			array_push($where,['nurse_id_one','>',0]);
			array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
			$arr3 =Db::name('service_log')
			    ->field('nurse_id_two as personId,category_id')
			    ->where($where)
			    ->select()->toArray();
			$result = array();
			foreach($arr1 as $val){
			    $key = $val['personId'].'_'.$val['category_id'];
			    if(!isset($result[$key])){
			        $val['number'] = 1;
			        $result[$key] = $val;
			    }else{
			        $result[$key]['number'] += 1;
			    }
			}
			foreach($arr2 as $val){
			    $key = $val['personId'].'_'.$val['category_id'];
			    if(!isset($result[$key])){
			        $val['number'] = 0.5;
			        $result[$key] = $val;
			    }else{
			        $result[$key]['number'] += 0.5;
			    }
			}
			foreach($arr3 as $val){
			    $key = $val['personId'].'_'.$val['category_id'];
			    if(!isset($result[$key])){
			        $val['number'] = 0.5;
			        $result[$key] = $val;
			    }else{
			        $result[$key]['number'] += 0.5;
			    }
			}

			$category =$this->getPushCategoryArray();
			foreach ($list as $key=>$value){

				foreach($category as $k=>$v){

					$id =$v['id']??0;
					$keys =$value['id'].'_'.$id;

					$category[$k]['number'] =$result[$keys]['number']??0;
					$category[$k]['yuangongID'] =$value['id'];
				}

				 $list[$key]['goods'] =$category;

			}

			$newsList = [];

			foreach ($list as $key=>$value){
				$nurseCountT =$this->getNurseDateCount($value['id'],$startDataTime,$endDataTime);
				$huliTotal = 0;
				foreach($value['goods'] as $k1=>$v1){

					if($v1['yuangongID'] == $value['id']){

						$newsList[$key]['id'] = $value['id'];
						$newsList[$key]['shop_id'] = $value['shop_id'];
						$newsList[$key]['shop_name'] = $value['shop_name'];
						$newsList[$key]['name'] = $value['name'];
						$newsList[$key]['market_name'] = $value['market_name'];
						$newsList[$key]['station_name'] = $value['station_name'];

						if($v1['id'] == 1){
							$newsList[$key]['bahennum'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}
						if($v1['id'] == 4){
							$newsList[$key]['jingluotong'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}

						if($v1['id'] == 8){
							$newsList[$key]['mianbunum'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}

						if($v1['id'] == 10){
							$newsList[$key]['shentinum'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}

						if($v1['id'] == 11){
							$newsList[$key]['shengming'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}

						if($v1['id'] == 12){
							$newsList[$key]['shuganliqi'] = $v1['number'];
							$huliTotal +=$v1['number'];
						}
						//基础补水 没有办法归类暂时不做计算  2022-04-18
						$newsList[$key]['jichubushui'] = 0;
						$newsList[$key]['total'] = $huliTotal;

						$newsList[$key]['daycount'] = $nurseCountT;
					}

				}
			}

		}

		$data              = [];

		$data['service_log']      = $newsList ?? [];

		$data['dataCount']        = $dataCount ?? 0;

		return $data;

	}




    /**
     * 获取服务列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getLogList(array $request): array
    {
        try {
            $serviceId = $request['serviceId'] ?? 0;
            $customerId = $request['customerId'] ?? 0;
            if ($serviceId) {
                $logWhere = [
                    ['service_id', '=', $serviceId]
                ];
            }
            if ($customerId){
                $serviceIds = $this->where('customer_id', '=', $customerId)->column('id');
                $logWhere = [
                    ['service_id', 'in', $serviceIds]
                ];
            }
            // $logWhere['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            // $logWhere['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            // print_r($logWhere);exit;
            $logList = Db::name('service_log')->where($logWhere)->select()->toArray();
            if ($logList) {
                $oneId     = array_column($logList, 'nurse_id_one');
                $twoId     = array_column($logList, 'nurse_id_two');
                $userIdArr = array_unique(array_merge($oneId, $twoId));
                $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
                $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
                foreach ($logList as $key => $val) {
                    $logList[$key]['nurse_id_one_name'] = $userList[$val['nurse_id_one']] ?? '';
                    $logList[$key]['nurse_id_two_name'] = $userList[$val['nurse_id_two']] ?? '';
                    $logList[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $logList[$key]['end_time']          = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $logList[$key]['create_time']       = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '';
                    $logList[$key]['comment_time']       = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                }
            }
            $info['service_log'] = $logList;

            return $info;
        } catch (\Exception $e) {

        }

        return [];
    }
    /**
     * 获取服务数据集
     */
    public function readServiceList(array $request): array
    {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];
        $export = $request['export'] ?? 0;
        if ($export == 1){
            $ids = $request['id'] ?? [];
            array_push($where,['id','in',$ids]);
        }
        $shopIds = $request['shopIds'] ?? [];
        array_push($where,['id','in',$shopIds]);
        $list  = Db::name('service_log')->where($where)->order('id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
        $dataCount = Db::name('service_log')->where($where)->count();

        $serviceIds     = array_column($list, 'service_id');
        //获取服务列表
        $zlist = Db::name('service')->where([['id','in',$serviceIds]])->column(['id','name','shop_id','customer_id','service_type','num','start_time','end_time','create_time','last_service_time','status','experience'],'id');
        //获取店铺数据
        $shopIds     = array_column($list, 'shop_id');
        $shoplist = Db::name('shop')->where([['shop_id','in',$shopIds]])->column(['id','shop_name','shop_id','market_name'],'shop_id');
        //获取客户数据
        $customerIds     = array_column($list, 'customer_id');
        $customerlist = Db::name('customer')->where([['id','in',$customerIds]])->column(['id','customer_name','sex','age'],'id');
        //获取护理师
        $oneId     = array_column($list, 'nurse_id_one');
        $twoId     = array_column($list, 'nurse_id_two');
        $userIdArr = array_values(array_unique(array_merge($oneId, $twoId)));
        $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
        $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
        // 客户名称
        // 服务日期
        // 性别
        // 年龄
        // 门店
        // 市场
        // 卡项名称
        // 护理1
        // 护理2
        // 服务类型
        foreach ($list as $key => $val){
            // print_r($customerlist);exit();
            $list[$key]['customer_name']        = $customerlist[$val['customer_id']]['customer_name'] ?? "";
            $list[$key]['start_time']        = date('Y-m-d H:i:s',$list[$key]['start_time']);
            $list[$key]['sex']        = $customerlist[$val['customer_id']]['sex'] ?? 0;
            $list[$key]['age']        = $customerlist[$val['customer_id']]['age'] ?? 0;
            $list[$key]['shop_name']        = $shoplist[$val['shop_id']]['shop_name'] ?? "";
            $list[$key]['market_name']        = $shoplist[$val['shop_id']]['market_name'] ?? "";
            $list[$key]['name']        = $zlist[$val['service_id']]['name'] ?? "";
            $list[$key]['nurse_id_name']        = $userList[$val['nurse_id_one']] ?? "";
            if (isset($userList[$val['nurse_id_two']])){
                $list[$key]['nurse_id_name'] = $list[$key]['nurse_id_name'].'，'.$userList[$val['nurse_id_two']];
            }
            $list[$key]['service_type']        = $zlist[$val['service_id']]['service_type'] ?? 1;
        }

        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 新增服务记录
     */
    public function addServiceLog(array $request): array
    {
        try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                $this->error = '数据格式错误';
                return [];
            }
            $serviceInfo = $this->where('id','=',$serviceId)->find();
           
            if($serviceInfo['service_type'] == 1){
                if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                    $this->error = '不在服务时间内，无法进行核销';
                    return [];
                }
            }
            $num = $request['num'] ?? 0;
            if($num == 0){
                $this->error = '服务次数不能为0';
                return [];
            }
            $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
            if(bcadd($num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                $this->error = '超过服务次数无法进行核销';
                return [];
            }
            // echo 222;die;
            $orderGoods = $this->getOrderGoodsInfo($serviceInfo['order_id'],$serviceInfo['goods_id']);
            $serviceData = DB::name('service')->where('id',$serviceId)->find();
            $consume_gratuity =  $serviceData['service_max_num']>0 ?bcdiv($serviceData['consume_gratuity'], $serviceData['service_max_num'], 2):0; //单次消耗的赠金
            $consume_money = $serviceData['service_max_num']>0 ? bcdiv($serviceData['consume_money'], $serviceData['service_max_num'], 2):0; //单次消耗的本金
            $consume_store_transfer = $serviceData['service_max_num']>0 ? bcdiv($serviceData['consume_store_transfer'], $serviceData['service_max_num'], 2):0; //单次消耗的店转
            $logData['create_time'] = time();
            $benyueCancel = $this->getMonthEnterShopNum($logData,$serviceData);
            $alreadyCancel = Db::name('service_log')->where('service_id',$serviceId)->where('is_cancel',0)->column('id');
            $alreadyCancelCount = count($alreadyCancel);
            $needNoZeronum = 0;
            if($serviceData['service_type'] == 1){
                $needNoZeronum = $benyueCancel-$alreadyCancelCount;
            }else{
                $needNoZeronum = $serviceData['num']-$alreadyCancelCount;
            }
            $addDataAll = [];

            for($i=1;$i<=$num;$i++){
                $addData = [];
                if($i<=$needNoZeronum){
                    $addData['consume_gratuity'] = $consume_gratuity;
                    $addData['consume_money'] = $consume_money;
                    $addData['consume_store_transfer'] = $consume_store_transfer;
                }else{
                    $addData['consume_gratuity'] = 0;
                    $addData['consume_money'] = 0;
                    $addData['consume_store_transfer'] = 0;
                }
                $addData['service_id']  = $serviceId;
                $addData['nurse_id_one']= $request['nurse_id_one'] ?? 0;
                $addData['nurse_id_two']= $request['nurse_id_two'] ?? 0;
                $addData['start_time']  = isset($request['start_time']) ? strtotime($request['start_time']) : 0;
                $addData['end_time']    = isset($request['end_time']) ? strtotime($request['end_time']) : 0;;
                $addData['comment_time']    = isset($request['comment_time']) ? strtotime($request['comment_time']) : 0;;
                $addData['create_time'] = time();
                $addData['customer_id'] = $request['customer_id'] ?? 0;
                $addData['shop_id']     = $request['shop_id'] ?? 0;
                $addData['pt']     = $request['pt'] ?? 0;
                $addData['category_id']     = $serviceInfo['category_id'] ?? 0;
                $addData['goods_id']     = $serviceInfo['goods_id'] ?? 0;
                $addData['nurse_one'] = $addData['nurse_two'] = 0;
                $addData['nurse_one_project'] = $addData['nurse_two_project'] = '';
                if(!empty($orderGoods)){
                    $addData['nurse_one'] = $orderGoods['nurse_one'];
                    $addData['nurse_two'] = $orderGoods['nurse_two'];
                    $addData['nurse_one_project'] = $orderGoods['nurse_one_project'];
                    $addData['nurse_two_project'] = $orderGoods['nurse_two_project'];
                }
                array_push($addDataAll,$addData);
            }
            // var_dump($addDataAll);die;
            if($addData['nurse_id_one'] == 0){
                $this->error = '请选择一号护理师';
                return [];
            }
            if($addData['customer_id'] == 0 || $addData['customer_id'] != $serviceInfo['customer_id']){
                $this->error = '服务客户错误';
                return [];
            }
            // if($addData['start_time'] = 0 || $addData['end_time'] = 0){
            //     $this->error = '请选择服务的开始时间和结束时间';
            //     return [];
            // }
            // if($addData['start_time'] > $addData['end_time']){
            //     $this->error = '开始时间不能大于结束时间';
            //     return [];
            // }
            $saveCustomer['final_service'] = time();
            Db::name('customer')->where('id','=',$addData['customer_id'])->update($saveCustomer);
            if (bcadd($num,$sy_num) == $serviceInfo['num']) {
                $saveData = [
                    'status'=>2,
                    'gb_end_time'=>time(),
                ];
                 $this->where('id','=',$serviceId)->save($saveData);
            }
            Db::name('service_log')->insertAll($addDataAll);
            $this->error = '添加服务记录成功';
            return ['id'=>0];
        } catch (\Exception $e) {
            // var_dump($e);
            $this->error = '添加服务记录失败';
            return [];
        }
    }

    //获取出库单-商品对应的护理师12及服务项12
    public function getOrderGoodsInfo($order_id,$order_goods_id){
        $data = DB::name('shop_order_goods')
            ->where(['order_id'=>$order_id,'goods_id'=>$order_goods_id])
            ->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')
            ->find();
        if(!empty($data)){
             $shop_order_goods_option_data = DB::name('shop_order_goods_option_log')
            ->where(['order_id'=>$order_id,'shop_order_goods_id'=>$data['id'],'is_new'=>1])
            ->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')
            ->find();
           
            if(!empty($shop_order_goods_option_data)){
                return $shop_order_goods_option_data;
            }
        }
        return $data;
       
    }

    public function getMonthEnterShopNum($logData,$serviceData){

        $cancel_time = $logData['create_time'];
        //核销的年份
        $year_cancel = date('Y',$cancel_time);
        //核销的月份
        $month_cancel = date('m',$cancel_time);
        $yearMonthCancel = date('Ym',$cancel_time);
        //服务开始时间
        $service_begin_time = $serviceData['start_time'];
        $service_begin_time_year = date('Y',$service_begin_time);
        $service_begin_time_month = date('m',$service_begin_time);
        $service_begin_time_yearMonth = date('Ym',$service_begin_time);

        //服务结束时间
        $service_end_time = $serviceData['end_time'];
        $service_end_time_year = date('Y',$service_end_time);
        $service_end_time_month = date('m',$service_end_time);
        $service_end_time_yearMonth = date('Ym',$service_end_time);

        if($service_begin_time_yearMonth == $service_end_time_yearMonth ){  //同年同月
            $max_cancel_num = $serviceData['first_month_max_service_num'];
        }else{
            if($service_begin_time_year == $service_end_time_year){
                //同年
                if($month_cancel ==$service_begin_time_month ){
                    $max_cancel_num = $serviceData['first_month_max_service_num'];
                }elseif($month_cancel == $service_end_time_month){
                    $max_cancel_num = $serviceData['end_month_max_service_num'];
                }else{
                    $max_cancel_num = $serviceData['middle_month_max_service_num'];
                }
            }else{
                //跨年
                if($year_cancel == $service_begin_time_year){
                    if($month_cancel == $service_begin_time_month){
                        $max_cancel_num = $serviceData['first_month_max_service_num'];
                    }else{
                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }
                }elseif($year_cancel == $service_end_time_year){
                    if($month_cancel == $service_end_time_month){
                        $max_cancel_num = $serviceData['end_month_max_service_num'];
                    }else{
                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }
                }
            }
        }
        return $max_cancel_num;
    }
        /**
     * 新增服务记录
     */
    public function addServiceLog2(array $request): array
    {
        // try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                $this->error = '数据格式错误';
                return [];
            }
            $serviceInfo = $this->where('id','=',$serviceId)->find();
            if(empty($serviceInfo)){
                $this->error = '服务不存在';
                return [];
            }
            if($serviceInfo['service_type'] == 1){
                if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                    $this->error = '不在服务时间内，无法进行核销';
                    return [];
                }
            }
            $num = $request['num'] ?? 0;
            if($num == 0){
                $this->error = '服务次数不能为0';
                return [];
            }
            $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
            if(bcadd($num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                $this->error = '超过服务次数无法进行核销';
                return [];
            }
            $key = $request['key'] ?? 0;
            if($key == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('service_id','=',$serviceId)->order('id desc')->find();
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $key){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            for($i=1;$i<=$num;$i++){
                $addData = [];
                $addData['service_id']  = $serviceId;
                $addData['nurse_id_one']= $request['nurse_id_one'] ?? 0;
                $addData['nurse_id_two']= $request['nurse_id_two'] ?? 0;
                $addData['start_time']  = isset($request['start_time']) ? strtotime($request['start_time']) : 0;
                $addData['end_time']    = isset($request['end_time']) ? strtotime($request['end_time']) : 0;;
                $addData['create_time'] = time();
                $addData['customer_id'] = $request['customer_id'] ?? 0;
                $addData['shop_id']     = $request['shop_id'] ?? 0;
                $addData['pt']          = $request['pt'] ?? 0;
                $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                $addData['key']         = $key;
                $addData['status']      = 0;
                array_push($addDataAll,$addData);
            }

            if($addData['nurse_id_one'] == 0){
                $this->error = '请选择一号护理师';
                return [];
            }
            if($addData['customer_id'] == 0 || $addData['customer_id'] != $serviceInfo['customer_id']){
                $this->error = '服务客户错误';
                return [];
            }
            // if($addData['start_time'] = 0 || $addData['end_time'] = 0){
            //     $this->error = '请选择服务的开始时间和结束时间';
            //     return [];
            // }
            // if($addData['start_time'] > $addData['end_time']){
            //     $this->error = '开始时间不能大于结束时间';
            //     return [];
            // }

            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        // } catch (\Exception $e) {
        //     $this->error = '添加服务记录失败';
        //     return [];
        // }
    }
     /**
     * 新增服务记录
     */
    public function gbservice(array $request): array
    {
        try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                $this->error = '数据格式错误';
                return [];
            }
            $serviceInfo = $this->where('id','=',$serviceId)->find();

            $saveData = [
                    'status'=>3,
                    'gb_end_time'=>time()
                ];
            $this->where('id','=',$serviceId)->save($saveData);
            $this->error = '服务已关闭';
            CustomerPointModel::pointChange($serviceInfo['customer_id'],5);
            return ['id'=>$serviceId];
        } catch (\Exception $e) {
            $this->error = '服务关闭失败';
            return [];
        }
        // return [];
    }

         /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getNoUseDataList(array $request): array
    {
        try {
            $customerId       = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : '';
            $serverIds       = $request['serverIds'] ??  '';
            if(empty($customerId)){
                $this->error = '客户数据不存在';
                return [];
            }
            $nurseId       = isset($request['nurse_id']) && intval($request['nurse_id']) ? intval($request['nurse_id']) : '';
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;
            //核验客户和员工是否是同一家店
            $personInfo = Db::name('shop_person')->where('id','=',$nurseId)->find();
            $customerInfo = Db::name('customer')->where('id','=',$customerId)->find();
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = $customerInfo['telephone'];
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                // print_r($customerList);exit;
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customerId = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if($customerInfo['shop_id'] != $personInfo['shop_id']){
                $this->error = '非本店客户，无法进行核销';
                return [];
            }
            $where = [];
            //处理过期的数据
            array_push($where,['customer_id','=',$customerId]);
            array_push($where,['service_type','=',1]);
            array_push($where,['end_time','<=',time()]);
            $this->where($where)->update(['status'=>2]);
            $where = [];
            array_push($where,['customer_id','=',$customerId]);
            array_push($where,['status','=',1]);
            if($serverIds){
                array_push($where,['id','in',explode(',',$serverIds)]);
            }
            // array_push($where,['start_time','>=',time()]);
            // array_push($where,['end_time','<=',time()]);
            // print_r($serverIds);exit;
            $list  = $this->where($where)->order('id DESC')->select()->toArray();
            // print_r($list);exit;

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;
            if($list){
                 $shop_idArr = array_values(array_unique(array_column($list, 'shop_id')));
                $shopList = Db::name('shop')->where('shop_id','in',$shop_idArr)->column('shop_name', 'shop_id');
                $serviceIdArr = array_values(array_unique(array_column($list, 'id')));
                $service_logList = Db::name('service_log')->group('service_id')->column(['count(id)'], 'service_id');
                $serviceTypeArr = ['1' => '按期', '2' => '按次'];
                foreach ($list as $key => $val) {
                    if($val['service_type'] == 1 && $val['start_time']>time()){
                        continue;
                    }
                    $list[$key]['service_type_name'] = $serviceTypeArr[$val['service_type']] ?? '';
                    $list[$key]['last_service_time'] = $val['last_service_time'] ? date('Y-m-d H:i:s', $val['last_service_time']) : '';
                    $list[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $list[$key]['end_time']     = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $list[$key]['sy_num']       = $service_logList[$val['id']] ?? 0;
                    $list[$key]['yy_num']       = bcsub($val['num'],$list[$key]['sy_num']);
                }
                $list = array_values($list);
            }
            $data              = [];
            $data['list']      = $list ?? [];
            return $data;
        } catch (\Exception $e) {
            $this->error = '服务列表为空2';
            return [];
        }
        $this->error = '服务列表为空';
        return [];
    }

    /**
     * 新增服务记录
     */
    public function addServiceLog3(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        try{
            // $add = [
            //         [
            //             'service_id'    =>26,
            //             'fw_num'        =>28,
            //         ],
            //         [
            //             'service_id'    =>25,
            //             'fw_num'        =>28,
            //         ]
            //     ];

            //     print_r(json_encode($add));exit;

            $serviceList = $request['serviceList'] ?? [];
            // $serviceList = $add;
            $keys = $request['key'] ?? '';
            // print_r($key);exit;
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            // mark 备注
            $mark = $request['mark'] ?? 0;

            $bookId = $request['bookId'] ?? 0;
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            // $shop_id = $request['shop_id'] ?? 0;
            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }
            // print_r($serviceList);exit;
            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                // print_r($customerList);exit;
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            // print_r($cunzaikeyFind);exit;
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            foreach ($serviceList as $key => $val){
                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    // code...
                    $this->error = '请录入服务记录';
                    return [];
                }
                $serviceInfo = $this->where('id','=',$serviceId)->find();
                if(empty($serviceInfo)){
                    $num = bcadd($key,1);
                    $this->error = '第【'.$num.'】条服务不存在';
                    return [];
                }
                if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                    $this->error = '服务客户错误';
                    return [];
                }
                if($serviceInfo['service_type'] == 1){
                    if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                        $this->error = '不在服务时间内，无法进行核销';
                        return [];
                    }
                }
                if($fw_num == 0){
                    $this->error = '服务次数不能为0';
                    return [];
                }
                $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                    $this->error = '超过服务次数无法进行核销';
                    return [];
                }
                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    array_push($addDataAll,$addData);
                }

            }

            // xy_book_uselog 预约数据核销记录表
            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";

            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($updateUseLog);
                // echo "</pre>";

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);

                // echo "111";echo "<br/>";
                // var_dump($bool);

            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($addUseLog);
                // echo "</pre>";


                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

                // echo "222";echo "<br/>";
                // var_dump($log_id);

            }

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";
            // exit;

            // $cunzaikeyFind = Db::name('service_log_mini')->where('service_id','=',$serviceId)->order('id desc')->find();
            // $cunzaikey = $cunzaikeyFind['key'] ?? '';
            // if($cunzaikey != $key){
            //     $this->error = '客户已更新服务二维码，请重新扫码';
            //     return [];
            // }


            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            // print_r($addDataAll);exit;
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        } catch (\Exception $e) {
            $this->error = '添加服务记录失败';
            return [];
        }
    }


    public function addServiceLog5(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        // try{
            // $add = [
            //         [
            //             'service_id'    =>26,
            //             'fw_num'        =>28,
            //         ],
            //         [
            //             'service_id'    =>25,
            //             'fw_num'        =>28,
            //         ]
            //     ];

            //     print_r(json_encode($add));exit;
            $serviceList = $request['serviceList'] ?? [];
            // $serviceList = $add;
            $keys = $request['key'] ?? '';
            // print_r($key);exit;
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            // mark 备注
            $mark = $request['mark'] ?? 0;

            $bookId = $request['bookId'] ?? 0;
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            // $shop_id = $request['shop_id'] ?? 0;
            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }
            // print_r($serviceList);exit;
            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            //todo
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            foreach ($serviceList as $key => $val){
                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    // code...
                    $this->error = '请录入服务记录';
                    return [];
                }
                $serviceInfo = $this->where('id','=',$serviceId)->find();
                if(empty($serviceInfo)){
                    $num = bcadd($key,1);
                    $this->error = '第【'.$num.'】条服务不存在';
                    return [];
                }
                if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                    $this->error = '服务客户错误';
                    return [];
                }
                if($serviceInfo['service_type'] == 1){
                    if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                        $this->error = '不在服务时间内，无法进行核销';
                        return [];
                    }
                }
                if($fw_num == 0){
                    $this->error = '服务次数不能为0';
                    return [];
                }
                $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                    $this->error = '超过服务次数无法进行核销';
                    return [];
                }
                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    array_push($addDataAll,$addData);
                }

            }

            // xy_book_uselog 预约数据核销记录表
            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";

            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($updateUseLog);
                // echo "</pre>";

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);

                // echo "111";echo "<br/>";
                // var_dump($bool);

            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($addUseLog);
                // echo "</pre>";


                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

                // echo "222";echo "<br/>";
                // var_dump($log_id);

            }

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";
            // exit;

            // $cunzaikeyFind = Db::name('service_log_mini')->where('service_id','=',$serviceId)->order('id desc')->find();
            // $cunzaikey = $cunzaikeyFind['key'] ?? '';
            // if($cunzaikey != $key){
            //     $this->error = '客户已更新服务二维码，请重新扫码';
            //     return [];
            // }


            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            // print_r($addDataAll);exit;
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        // } catch (\Exception $e) {
        //     $this->error = '添加服务记录失败';
        //     return [];
        // }
    }

    // 核销测试
    public function addServiceLogCeshi(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;


            $serviceList = $request['serviceList'] ?? [];
            $service_type = $request['type'] ?? [];
            // $serviceList = $add;
            $keys = $request['key'] ?? '';
            // print_r($key);exit;
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            // mark 备注
            $mark = $request['mark'] ?? 0;

            $bookId = $request['bookId'] ?? 0;
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            // $shop_id = $request['shop_id'] ?? 0;
            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }
            // print_r($serviceList);exit;
            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }

            // echo "1";
            // echo "<br/>";
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            // echo "2";
            // echo "<br/>";
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            //todo
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            // echo "3";
            // echo "<br/>";
            $addDataAll = [];
            foreach ($serviceList as $key => $val){
                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    // code...
                    $this->error = '请录入服务记录';
                    return [];
                }
                if($service_type == 1){
                    $serviceInfo = $this->where('id','=',$serviceId)->find();
                    if(empty($serviceInfo)){
                        $num = bcadd($key,1);
                        $this->error = '第【'.$num.'】条服务不存在';
                        return [];
                    }
                    if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                        $this->error = '服务客户错误';
                        return [];
                    }
                    if($serviceInfo['service_type'] == 1){
                        if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                            $this->error = '不在服务时间内，无法进行核销';
                            return [];
                        }
                    }
                    if($fw_num == 0){
                        $this->error = '服务次数不能为0';
                        return [];
                    }
                    $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                    if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                        $this->error = '超过服务次数无法进行核销';
                        return [];
                    }
                }

                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    $addData['service_type']= $service_type;
                    array_push($addDataAll,$addData);
                }

            }

            // echo "4";
            // echo "<br/>";
            // xy_book_uselog 预约数据核销记录表
            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";

            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($updateUseLog);
                // echo "</pre>";

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);


            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($addUseLog);
                // echo "</pre>";


                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

            }
            // echo "5";
            // echo "<br/>";
            // exit;

            // if($service_type == 2){
            //     echo "<pre>";
            //     print_r($addDataAll);
            //     echo "</pre>";
            //     exit;
            // }


            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];


    }

	//查询护理师当天的护理量数据
	public function getNurseDateCount($nurseId,$starTime,$endTime){

		$where = [];
		array_push($where,['nurse_id_one','=',$nurseId]);
		array_push($where,['create_time','>=',$starTime]);
		array_push($where,['create_time','<=',$endTime]);

		$nurseCount = Db::name('service_log')->distinct(true)->field('customer_id')->where($where)->count();

		return $nurseCount;
	}

	public function getPushCategoryArray(){
	    return [
	        [
	            'id'=>1,
	            'goodsName'=>'疤痘护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>8,
	            'goodsName'=>'面部护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>10,
	            'goodsName'=>'项目身体护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>11,
	            'goodsName'=>'生命之源',
	            'percentage'=>6,
	        ],
			[
			    'id'=>4,
			    'goodsName'=>'经络通',
			    'percentage'=>6,
			],

	        [
	            'id'=>12,
	            'goodsName'=>'疏肝理气',
	            'percentage'=>6,
	        ]
	    ];
	}

	public function delservicelog(array $request): array
	{


		$servicelogId = $request['id'] ?? 0;

		if ($servicelogId == 0){
			$this->error = '数据格式错误';
			return [];
		}else{
			//var_dump('到此一游');
			Db::name('service_log')->where('id','=',$servicelogId)->delete();
			$this->error = '服务记录作废成功';
			return [];
		}

	}


    public function changeService($request)
    {
        // echo "调整服务卡项";echo "<br/>";
        // echo "<pre>";
        // print_r($request);
        // exit;

        $service_id = $request['service_id'];

        $where = [];
        array_push($where,['update_id','=',$service_id]);
        array_push($where,['sh_type','=','0']);

        $res = Db::name('update_log')->where($where)->select()->toArray();

        if($res){
            $this->error = '提交正在审核中，请勿重复提交！';
            return [];
        }else{
            // try {

                if($request['service_type']==2){
                    $old = $request['old_num'];
                    $new = $request['num'];
                }

                if($request['service_type']==1){
                    $old = date('Y-m-d',strtotime($request['old_time']));
                    $new = $request['end_time'];
                }

                $insertDate = [
                    'type'        => 1,
                    'update_id'   => $request['service_id'],
                    'shop_id'     => $request['shop_id'] ?? '',
                    'old_date'    => $old,
                    'new_date'    => $new,
                    'creator_id'  => $request['user_id'],
                    'create_time' => time(),
                    'customer_id' => $request['customer_id'],
                ];


                // echo "<pre>";
                // print_r($insertDate);
                // exit;

                $id = Db::name('update_log')->insertGetId($insertDate);

                $this->error = '修改服务提交成功';
                return ['id'=>$id];
            // } catch (\Exception $e) {
            //     $this->error = '修改服务提交失败';
            //     return [];
            // }
        }


    }


    public function auditList($request)
    {

        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];
        $shop_ids = $request['shopIds'] ?? '';

        if($shop_ids){
            array_push($where,['shop_id','in',$shop_ids]);
        }

        // echo "<pre>";
        // print_r($where);
        // exit;
        $dataCounts = Db::name('update_log')->where($where)->count();

        $update_list = Db::name('update_log')->where($where)->order('id desc')->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->select()->toArray();

        $shopIds = array_values(array_unique(array_column($update_list, 'shop_id')));

        $operatorIds = array_values(array_unique(array_column($update_list, 'creator_id')));

        //获取店铺数据
        $shopList = Db::name('shop')->where('shop_id', 'in', $shopIds)->column('shop_name', 'shop_id');

        //获取员工姓名
        $creatorList = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');

        $list = [];
        foreach ($update_list as $key => $value) {
            $one = [];
            if($value['type']==1){
                $type = '卡项';
                $name = Db::name('service')->where('id','=',$value['update_id'])->value('name');
            }

            $one['name'] = $name;

            $one['type'] = $type;

            $one['shop_id']      = $shopList[$value['shop_id']] ?? '';

            $one['old_date'] = $value['old_date'];

            $one['new_date'] = $value['new_date'];

            $one['sh_type'] = $value['sh_type'] == 0 ? '未审核' : '已审核';

            $one['create_time'] = $value['create_time'] ? date('Y-m-d',$value['create_time']) : '';

            $one['sh_time'] = $value['sh_time'] ? date('Y-m-d',$value['sh_time']) : '';

            $one['update_id'] = $value['update_id'];

            $one['id'] = $value['id'];

            $one['shop_id']      = $creatorList[$value['creator_id']] ?? '';

            $one['sh_id']      = $creatorList[$value['sh_id']] ?? '';

            array_push($list,$one);
        }

        /**总数统计**/
        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCounts ?? 0;
        return $data;
    }

    public function submitAudit($request)
    {

        try {
            $id = $request['id'] ?? '';

            $where = [];
            if($id){
                array_push($where,['id','=',$id]);
            }

            $update_info = Db::name('update_log')->where($where)->column('update_id,type,old_date,new_date');

            if($update_info[0]['type']=='1'){
                // 卡项修改
                $service_id = $update_info[0]['update_id'];

                $udate_array = [];

                $res = strtotime($update_info[0]['new_date']);
                if($res){
                    // echo "修改时间";
                    $udate_array['end_time'] = $res;

                    if($udate_array['end_time']<=time()){
                        // echo "卡项已过期";

                        $udate_array['status'] = '2';
                    }else{
                        $udate_array['status'] = '1';
                    }
                }else{
                    // echo "修改次数";
                    $udate_array['num'] = $update_info[0]['new_date'];

                    $userNum = Db::name('service_log')->where('service_id',$service_id)->count();

                    if($udate_array['num']<=$userNum){
                        // echo "超出使用次数";
                        $udate_array['status'] = '2';
                    }else{
                        $udate_array['status'] = '1';
                    }
                }

                $id_s = Db::name('service')->where('id',$service_id)->update($udate_array);

                // echo $id_s;
                // echo "<br/>";

                $data_u = [
                    'sh_id'   => $request['user_id'],
                    'sh_time' => time(),
                    'sh_type' => '1'
                ];

                // echo "<pre>";
                // print_r($udate_array);

                // echo "<pre>";
                // print_r($data_u);
                // exit;

                $id_u = Db::name('update_log')->where('id',$id)->update($data_u);


                // echo $id_u;
                // echo "<br/>";

                // exit;


            }

            $this->error = '审核成功';
            return ['msg'=>'审核成功'];

        } catch (\Throwable $e) {
            $this->error = '审核失败';
            return [];
        }

    }
     /**
     * 获取护理列表汇总
     */

     public function getTotalData(array $request): array
     {

         $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

         $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;


         $shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

         $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;

         $shopIds = $request['shopIds'] ?? [];

         $nowYear =  date('y'); //当前年
         $nowMonth =  date('m'); //当前月份
         $nowdata =  date('t'); //当前天数

         $startmonth = $nowYear.'-'.$nowMonth.'-'.'1';
         $endmonth = $nowYear.'-'.$nowMonth.'-'.$nowdata;

         $start_time = $request['start_time'] ?? '';
         if($start_time){

             $startTimeToday =strtotime($request['start_time']);
         }else{
             $startTimeToday =strtotime($startmonth);
         }

         $endTime = $request['endTime'] ?? '';

         if($endTime){

             $endTimeToday =strtotime($request['endTime'])+86399;
             $startDataTime = strtotime($request['endTime']);
             $endDataTime = strtotime($request['endTime'])+86399;

         }else{
             $endTimeToday =strtotime($endmonth)+86399;
             $startDataTime = strtotime(date('Y-m-d'));
             $endDataTime = strtotime(date('Y-m-d'))+86399;
         }

         $where      = [];

         $shopId && array_push($where, ['s.shop_id', '=', $shopId]);

         if($shopIds){

             array_push($where,['s.shop_id','in',$shopIds]);

         }

         $nurseName = $request['nurse_name'] ?? '';

         if($nurseName){

             array_push($where,['s.name','=',$nurseName]);

         }

         $category =$this->getPushCategoryArray();
         array_push($where, ['s.status', '<>', 3]);
         //array_push($where, ['sp.type', '=', 1]);

         // $dataCount = Db::name('shop_person')->alias('s')
         // 	    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
         // 	    ->where($where)->count();

         /*
             疤痘护理---- 1  | 面部护理---- 8 | 项目身体护理  ---10  | 生命之源/经络通/疏肝理气 --11 | 基础补水 --12
         */



             $field = ['s.id,s.shop_id,s.shop_name,s.name,s.market_name,s.station_name'];

             if($is_export == '1'){

                 $list  = Db::name('shop_person')->alias('s')

                     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                     ->where($where)

                     ->field($field)->order('s.shop_id DESC')

                     ->select()->toArray();

             }else{

                 $list  = Db::name('shop_person')->alias('s')

                     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                     ->where($where)

                     ->field($field)->order('s.shop_id DESC')

                     ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                     ->select()->toArray();

             }

             $list  = Db::name('shop_person')->alias('s')

                 ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                 ->where($where)

                 ->field($field)->order('s.shop_id DESC')

                 // ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                 ->select()->toArray();

             $pids =array_column($list,'id');
             $category =$this->getPushCategoryArray();
             $ids =array_column($category,'id');

             // 获取当天服务量
             // 比例为1的
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['nurse_id_two','=',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr1 =Db::name('service_log')
                 ->field('count(*) as total,category_id')
                 ->where($where)
                 ->group('category_id')
                 ->select()->toArray();
             //print_r($arr1);
             // 比例为0.5的
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['nurse_id_two','>',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr2 =Db::name('service_log')
             ->field('count(*) as total,category_id')
             ->where($where)
             ->group('category_id')
                 ->select()->toArray();
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_two','in',$pids]);
             array_push($where,['nurse_id_one','>',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr3 =Db::name('service_log')
             ->field('count(*) as total,category_id')
             ->where($where)
             ->group('category_id')
                 ->select()->toArray();
             $result = array();
             foreach($arr1 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total'];
                 }else{
                     $result[$val['category_id']] += $val['total'];
                 }
             }
             foreach($arr2 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total']*0.5;
                 }else{
                     $result[$val['category_id']] += $val['total']*0.5;
                 }
             }
             foreach($arr3 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total']*0.5;
                 }else{
                     $result[$val['category_id']] += $val['total']*0.5;
                 }
             }
             $huliTotal=0;
             $data = array();
             $data = [
                 'id'=>0,
                 'shop_id'=>0,
                 'shop_name'=>"",
                 'name'=>'',
                 'market_name'=>"汇总",
                 'station_name'=>"",
                 'bahennum'=>0,
                 'jichubushui'=>0,
                 'total'=>0,
                 'daycount'=>0,
                 'mianbunum'=>0,
                 'shentinum'=>0,
                 'shengming'=>0,
                 'jingluotong'=>0,
                 'shuganliqi'=>0
             ];
             foreach($result as $key => $val)
             {
                 if($key == 1){
                     $data['bahennum'] = $val;
                     $huliTotal += $val;
                 }
                 if($key == 4){
                     $data['jingluotong'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 8){
                     $data['mianbunum'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 10){
                     $data['shentinum'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 11){
                     $data['shengming'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 12){
                     $data['shuganliqi'] = $val;
                     $huliTotal += $val;
                 }
             }
             $where = [];

             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['create_time','>=',$startDataTime]);
             array_push($where,['create_time','<=',$endDataTime]);

             $nurseCount = Db::name('service_log')->distinct(true)->field('customer_id')->where($where)->count();

             //基础补水 没有办法归类暂时不做计算  2022-04-18
             $data['jichubushui'] = 0;
             $data['total'] = $huliTotal;
             $data['daycount'] = $nurseCount;




         return $data;

     }
}
